#include "headfiles.h"

using namespace std;

int main(int argc, char **argv) {
    if (argc != 3) {
        cout << "Usage: " << argv[0] << " file num" << endl;
        return 0;
    }

    string file_name(argv[1]);
    int num = atoi(argv[2]);

    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "Input file " << file_name << " open error!" << endl;
        return 1;
    }

    string str;
    fs >> str;
    int n = atoi(str.c_str());
    if (n <= 0) {
        cout << "Incorrect number of elements, " << n << "." << endl;
        return 1;
    }

    int *array = (int *)malloc(sizeof(int) * n);
    if (array == NULL) {
        cout << "Allocate array buffer error, NULL!" << endl;
        return 1;
    }

    int index = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        array[index++] = atoi(str.c_str());
    }
    fs.close();

    if (index != n) {
        cout << "The elements do not match the num" << endl;
        return 1;
    }

    index = modBinSearch(array, n, num);
    cout << "Index = " << index << endl;

    free(array);

    return 0;
}

